package ltd.bugs.cute.common.extention.factory.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.util.StringUtils;

import ltd.bugs.cute.common.extention.annotation.SpringBean;
import ltd.bugs.cute.common.spring.ApplicationContextHolder;

public class SpringExtensionFactory {

  private static Logger logger = LoggerFactory.getLogger(SpringExtensionFactory.class);

  public static <T> T newInstance(Class<T> type) throws Exception {
    SpringBean springBean = type.getAnnotation(SpringBean.class);
    // 判断当前context中是否存在，存在的话不再进行初始化，直接使用
    try {
      T bean = ApplicationContextHolder.getBean(springBean.beanName(), type);
      logger.info("get bean '{}' from spring context!", springBean.beanName());
      return bean;
    } catch (NoSuchBeanDefinitionException e) {
      // 当前spring context不存在bean，加载xml进行初始化
      // context不存在，进行加载
      if (StringUtils.isEmpty(springBean.xmlPath())) {
        throw new RuntimeException("bean's xml path can't be empty!");
      }
      logger.info("bean '{}' not exist in spring context, start to register!",
          springBean.beanName());
      ApplicationContextHolder.registerBean(springBean.xmlPath());

      return ApplicationContextHolder.getBean(springBean.beanName(), type);
    }
  }
}
